<?php

namespace App\Http\Api\Services;

use App\Exceptions\InvalidRequestException;
use App\Http\Models\Manu;
use App\Http\Models\Order;
use App\Http\Models\OrderSettlement;
use App\Http\Services\BaseService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class OrderService extends BaseService
{
    protected $liverRelation;
    protected $shopRelation;

    public function __construct()
    {
        $liverRelation = DB::table('admin_config')->where('conf_key', 'liver')->first()->conf_val;
        $this->liverRelation = !empty($liverRelation) ? json_decode($liverRelation, true) : [];
    }

    /*
     * code更新
     * */
    public function codeEdit($attributes)
    {
        if(!is_array($attributes)){
            $attributes = json_decode($attributes,true);
        }
        if(count($attributes) > 0){
            foreach ($attributes as $item){
                $tmp = [];
                $spec_desc = array();
                if(!empty($item['spec_desc'])){
                    foreach ($item['spec_desc'] as $k => $v) {
                        $spec_desc[$v['name']] = $v['value'] ?? '';
                    }
                }
                if(!empty($item['code'])){
                    $spec_desc['额外'] = $item['code'];
                    if (strpos($item['code'], '#') != false) {
                        $tmp_arr_code = explode('#', $item['code']);
                        if (!empty($tmp_arr_code[2])) {
                            if (is_numeric($tmp_arr_code[2])) {
                                $tmp['tmp_cost_price'] = $tmp_arr_code[2];
                            }
                        }
                        if (!empty($tmp_arr_code[0])) {
                            $tmp['manu_name'] = $tmp_arr_code[0];
                            if (strpos($tmp_arr_code[0], '玖纯') !== false) {
                                $tmp['tmp_cost_price'] = (int)($item['combo_amount'] * 0.7);
                            }
                        }
                        if (!empty($tmp_arr_code[1])) {
                            $tmp['prod_no'] = $tmp_arr_code[1];
                        }
                    }
                }
                if(!empty($spec_desc)){
                    $tmp['spec_desc'] = json_encode($spec_desc);
                }
                $flag = Order::where('order_id',$item['order_id'])->exists();
                if($flag){
                    $cost_price = Order::where('order_id',$item['order_id'])->first()->cost_price;
                    if($cost_price == 0){
                        $tmp['cost_price'] = !empty($tmp['tmp_cost_price'])? $tmp['tmp_cost_price']:0;
                    }
                    Order::where('order_id',$item['order_id'])->update($tmp);
                }
            }
        }
        return true;
    }

    /*
     * 订单采集
     * */
    public function store($attributes = [])
    {
        if (empty($attributes)) {
            throw new InvalidRequestException('参数错误 不能为空');
        }
        if (!is_array($attributes)) {
            $attributes = json_decode($attributes, true);
        }
        $this->shopRelation = DB::table('admin_shop_config')->get()->toArray();

        if (!empty($attributes)) {
            foreach ($attributes as $item) {
                if (!empty($item['order_id'])) {
                    $tmp_item = $this->orderItem($item);
                    if (Order::where('order_id', $item['order_id'])->exists()) {
                        Order::where('order_id', $item['order_id'])->update($tmp_item);
                    } else {
                        Order::create($tmp_item);
                    }
                }
            }
        }
        return true;
    }

    /*
     * 根据备注拆出关联字段
     * return array
     * */
    public function orderItem($item)
    {
        $tmp = [];
        $tmp['order_id'] = $item['order_id'];
        //父订单id
        $tmp['pid'] = !empty($item['pid']) ? $item['pid'] : '';
        //采集下来的商品id
        $tmp['origin_prod_id'] = !empty($item['origin_prod_id']) ? $item['origin_prod_id'] : '';
        //采集下来的商品名
        $tmp['origin_prod_name'] = !empty($item['origin_prod_name']) ? $item['origin_prod_name'] : '';


        //商品单价
        $tmp['combo_amount'] = !empty($item['combo_amount']) ? $item['combo_amount'] : 0;
        //商品数量
        $tmp['combo_num'] = !empty($item['combo_num']) ? $item['combo_num'] : 0;
        //平台优惠券
        $tmp['coupon_amount'] = !empty($item['coupon_amount']) ? $item['coupon_amount'] : 0;
        //商家优惠券
        $tmp['shop_coupon_amount'] = !empty($item['shop_coupon_amount']) ? $item['shop_coupon_amount'] : 0;


        //总价
        $tmp['total_amount'] = !empty($item['total_amount']) ? $item['total_amount'] : 0;
        //物流单号
        if (!empty($item['logistics_code'])) {
            $tmp['logistics_code'] = $item['logistics_code'];
        }

        //金额说明
        $tmp['amount_spec'] = !empty($item['amount_spec']) ? $item['amount_spec'] : '';
        //下单时间
        $tmp['create_time'] = null;
        if (!empty($item['create_time'])) {
            if (is_numeric($item['create_time'])) {
                $tmp['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
            } else {
                $tmp['create_time'] = $item['create_time'];
            }
        }

        //订单状态
        $tmp['order_status'] = !empty($item['order_status']) ? $item['order_status'] : 0;
        //收件人
        $tmp['post_receiver'] = !empty($item['post_receiver']) ? $item['post_receiver'] : '';
        //收件人电话
        $tmp['post_tel'] = !empty($item['post_tel']) ? $item['post_tel'] : '';
        //地址
        $tmp['province'] = !empty($item['province']) ? $item['province'] : '';
        $tmp['city'] = !empty($item['city']) ? $item['city'] : '';
        $tmp['town'] = !empty($item['town']) ? $item['town'] : '';
        $tmp['detail'] = !empty($item['detail']) ? $item['detail'] : '';
        //店铺
        $tmp['shop_name'] = !empty($item['shop_name']) ? $item['shop_name'] : '';
        $tmp['shop_id'] = !empty($item['shop_id']) ? $item['shop_id'] : '';

        //买家留言
        $tmp['buyer_words'] = !empty($item['buyer_words']) ? $item['buyer_words'] : '';
        //卖家留言
        $tmp['seller_words'] = !empty($item['seller_words']) ? $item['seller_words'] : '';

        //sku
        $tmp['sku_no'] = '';
        //主播
        $tmp['liver'] = '';
        //货号
        $tmp['prod_no'] = '';


        //根据产品名做出的操作
        //剥离出主播
        //剥离出货号

        if (!empty($tmp['origin_prod_name'])) {
            $prod_name = $tmp['origin_prod_name'];
            //剥离出主播
            if (!empty($this->liverRelation)) {
                foreach ($this->liverRelation as $liverItem) {
                    if (strpos($prod_name, $liverItem['nickname']) !== false) {
                        $tmp['liver'] = $liverItem['name'];
                        break;
                    }
                }
            }
            //剥离出货号
            $prod_no_pattern = '/[A-Za-z]+\d+/u';
            preg_match_all($prod_no_pattern, $prod_name, $res);
            if (!empty($res[0][0])) {
                $tmp['prod_no'] = $res[0][0];
            }

        }

        if (empty($tmp['liver']) && !empty($tmp['shop_id'])) {
            $shop = collect($this->shopRelation)->where('shop_id', $tmp['shop_id'])->first();
            $tmp['liver'] = $shop->liver;
        }



        //根据商户备注匹配出主播
        //剥离出sku
        if (!empty($item['seller_words'])) {
            //范丽斌+陈新发#BZ002#6斤装#米白色#福州发货#122333#170
            $pattern = "/[\S|\s]*\+[\S|\s]*\#[\S|\s]*\#[\S|\s]*/";
            if (preg_match($pattern, $item['seller_words'])) {
                $arr_liver = explode('+', $item['seller_words'])[0];
                if (!empty($arr_liver)) {
                    $tmp['liver'] = $arr_liver;
                }
                //剥离出sku
                $tmp_arr = explode('#', $item['seller_words']);
                $tmp['sku_no'] = !empty($tmp_arr[5]) ? $tmp_arr[5] : '';
                $tmp['manu_name'] = !empty($tmp_arr[4]) ? $tmp_arr[4] : '';
                //剥离出货号
                if (!empty($tmp_arr[1])) {
                    $tmp['prod_no'] = $tmp_arr[1];
                }

            }
        }
        //沈小小店铺特殊处理
        if ($tmp['create_time'] > '2019-12-10 13:00:00' && $tmp['shop_id'] == 77447) {
            $tmp['liver'] = '沈立妙';
        }
        return $tmp;
    }


    /*
     * 订单结算采集
     * */
    public function settStore($attributes = [])
    {
        if (empty($attributes)) {
            throw new InvalidRequestException('参数错误 不能为空');
        }
        if (!is_array($attributes)) {
            $attributes = json_decode($attributes, true);
        }
        $insert_count = 0;
        $update_count = 0;
        if (!empty($attributes)) {
            foreach ($attributes as $item) {
                $item['sett_collect_time'] = date('Y-m-d H:i:s', time());
                if (OrderSettlement::where('sett_order_id', $item['sett_order_id'])
                    ->where('sett_total_amount', $item['sett_total_amount'])
                    ->where('sett_payment_online', $item['sett_payment_online'])
                    ->exists()) {
                    OrderSettlement::where('sett_order_id', $item['sett_order_id'])
                        ->where('sett_total_amount', $item['sett_total_amount'])
                        ->where('sett_payment_online', $item['sett_payment_online'])
                        ->update($item);
                    $update_count++;
                } else {
                    OrderSettlement::create($item);
                    $insert_count++;
                }

            }
        }

        return [$insert_count, $update_count];
    }




    /*
     * 曲线图-主播订单统计（按照时间段）
     * */
    public function OrderCount($condition = []){

        $start_time =   $condition['start_time'] ??  date('Y-m-01', strtotime(date("Y-m-d")));
        $end_time   =   $condition['end_time'] ??  date("Y-m-d");

        //查询订单数据
        $raw = [
            DB::raw('sum(total_amount) as total_amount'),
            DB::raw('sum(cost_price)+sum(express_fee)+sum(packing_charge)+sum(unline_payment)+sum(unline_express_fee) as all_cost'),
            DB::raw('sum(total_amount)-sum(cost_price)-sum(express_fee)-sum(packing_charge)-sum(unline_payment)-sum(unline_express_fee) as all_profit'),
            DB::raw("date_format(create_time,'%Y-%m-%d') as time"),
            'liver',
        ];

        $data   =   Order::select($raw)->whereIn('order_status',[2,3,5,15,16,27,30,34,36,39])
                    ->whereBetween('create_time',[$start_time,$end_time])
                    ->groupBy('liver',DB::raw("date_format(create_time,'%Y-%m-%d')"))
                    ->get()->toArray();

        //主播
        $livers =   collect($data)->sortByDesc('total_amount')->unique('liver')->pluck('liver');

        //数据处理
        $statr=strtotime($start_time);
        $end=strtotime($end_time);
        $j=24*60*60; //一天的秒数

        $count_arr  =   [];
        foreach ($livers as $liver){
            $tmp_arr    =   collect($data)->where('liver',$liver)->values()->all();
            $arr    =   [];
            for ($i=$statr; $i < $end ; $i+=$j) {
                unset($tmp);
                $time=date('Y-m-d',$i);//格式化
                $tmp['total_amount']    =   0;
                $tmp['all_cost']        =   0;
                $tmp['all_profit']      =   0;
                $tmp['liver']           =   $liver;
                $tmp['time']            =   $time;
                foreach ($tmp_arr as $item){
                    if($item['time']    ==  $time){
                        $tmp            =   $item;
                    }

                }
                array_push($arr,$tmp);
            }
            array_push($count_arr,$arr);
        }

        return $count_arr;

    }


    /*退款率报表*/
    public function refundReport($condition    =   []){

        $start_time =   $condition['start_time'] ??  date('Y-m-01', strtotime(date("Y-m-d")));
        $end_time   =   $condition['end_time'] ??  date("Y-m-d");
        $count_type  =   $condition['count_type'] ?? 1;// 1 已发货退款率  2  所有订单退款率


        $raw    =   [
            DB::raw('count(order_id) as total_num'),
            DB::raw('sum(total_amount) as total_amount'),
            'manu_name',
        ];

        $modal   =   Order::select($raw);
        if($count_type == 1){
            $modal   =   $modal->where([['logistics_code','!=',''],['manu_name','!=','']]);

        }elseif($count_type == 2){
            $modal   =   $modal->whereNotIn('order_status',[1,4])->where('manu_name','!=','');
        }
        $modal  =   $modal->whereBetween('create_time',[$start_time,$end_time]);

        $modal1 =   clone ($modal);
        $total          =   $modal->groupBy('manu_name')->get()->toArray();
        $total_refund   =   $modal1->whereIn('order_status',[21,22,39])->groupBy('manu_name')->get()->toArray();

        $arr    =       [];
        foreach ($total as $item){
            $tmp_refund    =   collect($total_refund)->where('manu_name',$item['manu_name'])->first();
            unset($tmp);
            //退货率
            $tmp['total_num']           =   intval($item['total_num']) ?? 0;
            $tmp['total_refund_num']    =   intval($tmp_refund['total_num']) ?? 0;
            $tmp['refund_num_rate']     =   round(intval($tmp['total_refund_num'])/intval($tmp['total_num'])*100,2) ?? 0;
            //退款率
            $tmp['total_amount']        =   floor($item['total_amount']) ?? 0;
            $tmp['total_refund_amount'] =   floor($tmp_refund['total_amount']) ?? 0;
            $tmp['refund_amount_rate']  =   round(floor($tmp['total_refund_amount'])/floor($tmp['total_amount'])*100,2) ?? 0;
            $tmp['manu_name']           =   $item['manu_name'] ?? 0;
            array_push($arr,$tmp);
        }

        return $arr;
    }


}
